import React, { useState } from 'react';
import { Button,  message, Steps,  theme,   } from 'antd';
import FirstDom from './components/FirstDom';
import SecundaDom from './components/SecundaDom'
import type { PayListType } from '../../types/dom';
import ThirdDom from './components/ThirdDom';
import {simpleAmountToChinese,year,month,day} from '../../utils/china';

import Docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import type { HistoryData } from '../../types';
import { addHistoryApi } from '../../api';


const CreatePay: React.FC = () => {

  const { token } = theme.useToken();
  const [current, setCurrent] = useState(0);

  const [amount,setAmount] = useState<PayListType[]>([])
  const handleChildData = (receivedData:PayListType[])=>{
    console.log('收到子组件数据:', receivedData);
    setAmount(receivedData)
  }
  const next = () => {
    setCurrent(current + 1);
  };

  const prev = () => {
    setCurrent(current - 1);
  };
  const handleDownload = ()=>{
    message.success('开始下载!')
    console.log('开始了')
    createDocx()
  }
  const createDocx = async ()=>{
    // 上传至服务器
    const newArray = amount.map(item=>{
      return {
        year,
        month,
        day,
        name:item.name,
        account:item.account,
        bank_name:item.bank_name,
        amount:item.amount,
        remark:item.remark
      }
    })
    addHistoryList({data:newArray})
    // 读取模板文件
    const template = await fetch('./pay-modules.docx');
    console.log(template)
    const arrayBuffer = await template.arrayBuffer();
        // 处理模板
    const zip = new PizZip(arrayBuffer);
    const doc = new Docxtemplater(zip, {
    paragraphLoop: true,
    linebreaks: true,
    });
    const data = amount.map((item)=>{
      return{
        year,month,day,
        name:item.name,
        account:item.account,
        bank_name:item.bank_name,
        amount:item.amount,
        upAccount:simpleAmountToChinese(item.amount),
        remark:item.remark
      }
    })
    
    doc.setData({
      C:[
        ...data
      ]
    })
    // 渲染并生成
    doc.render();
    const out = doc.getZip().generate({
      type: "blob",
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    });

    // 下载
    const link = document.createElement('a');
    link.href = URL.createObjectURL(out);
    link.download = `${month}月付款表.docx`;
    link.click();
  }
  const addHistoryList = async (data:HistoryData)=>{
    const res = await addHistoryApi(data)
    if(res.data.code===10000){
      message.info({
        type:'success',
        content:'数据已上传云空间'
      })
    }
  }

  // 步骤条
  const steps = [
    {
      title: '选择企业名单',
      content: <FirstDom />,
    },
    {
      title: 'Second',
      content: <SecundaDom onDataChange={handleChildData}/>,
    },
    {
      title: 'Last',
      content: <ThirdDom payList={amount}/>,
    },
  ];
  const items = steps.map((item) => ({ key: item.title, title: item.title }));

  const contentStyle: React.CSSProperties = {
    lineHeight: '100%',
    textAlign: 'center',
    color: token.colorTextTertiary,
    backgroundColor: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    border: `1px dashed ${token.colorBorder}`,
    marginTop: 16,
    
  };

  return (
    <>
      <div style={{position:'relative'}}>
      {/* <div style style={contentStyle}> */}
      <div style={{height:'85%',overflow:'auto'}}>
        {steps[current].content}
      </div>
      <div >

      <Steps style={{ marginTop: 24,}} current={current} items={items} />
      <div style={{ marginTop: 24 }}>
        {current === 0 && (
          <Button type="primary" onClick={() => next()}>
            下一步
          </Button>
        )}
        {current === 1 && (
          <Button type="primary" onClick={() => next()}>
            下一步
          </Button>
        )}
        {current === steps.length - 1 && (
          <Button type="primary" onClick={() => handleDownload()}>
            完成
          </Button>
        )}
        {current > 0 && (
          <Button style={{ margin: '0 8px' }} onClick={() => prev()}>
            上一步
          </Button>
        )}
        </div>
      </div>
      </div>
    </>
  );
};

export default CreatePay;